package com.hardydou.system.controller;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hardydou.common.result.Result;
import com.hardydou.common.constant.Const.UserStatus;
import com.hardydou.common.controller.BaseController;
import com.hardydou.common.result.ResultHelper;
import com.hardydou.framework.log.anno.LogMetaInfo;
import com.hardydou.system.mapper.SystemUserMapper;
import com.hardydou.system.model.SystemDept;
import com.hardydou.system.model.SystemUser;
import com.hardydou.system.service.ISystemDeptService;
import com.hardydou.system.service.ISystemJobService;
import com.hardydou.system.service.ISystemUserService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.Map;

/**
 * @author hardy
 */
@Controller
@RequestMapping("/system/user")
@Api(tags = "用户管理")
@LogMetaInfo(module = "用户管理")
public class SysUserController extends BaseController {
    @Autowired
    ISystemUserService systemUserService;
    @Autowired
    ISystemDeptService deptService;

    @Autowired
    ISystemJobService jobService;

    @ApiIgnore
    @GetMapping("")
    public String index() {
        return "user/list";
    }


    @ApiIgnore
    @GetMapping("/add")
    public String add(long deptId, Model model) {
        SystemDept dept = deptService.findById(deptId);
        model.addAttribute("dept", dept);
        return "user/add";
    }


    @ApiIgnore
    @PostMapping("/add")
    public String add(SystemUser user, Model model) {
        systemUserService.addUser(user);
        SystemDept dept = deptService.findById(user.getDeptId());
        model.addAttribute("dept", dept);
        model.addAttribute("code", 200);
        model.addAttribute("message", "添加成功");
        return "user/add";
    }

    @ApiIgnore
    @GetMapping("/edit")
    public String edit(long userId, Model model) {
        SystemUser user = systemUserService.findByUserId(userId);
        SystemDept dept = deptService.findById(user.getDeptId());
        model.addAttribute("dept", dept);
        model.addAttribute("user", user);

        return "user/edit";
    }

    @ApiIgnore
    @PutMapping("/edit")
    public String edit(SystemUser user, Model model) {
        model.addAttribute("code", 200);
        model.addAttribute("message", "修改成功");
        systemUserService.update(user);
        model.addAttribute("user", user);
        return "user/edit";
    }


    @ApiIgnore
    @GetMapping("/info")
    public String info(long userId, Model model) {
        SystemUser user = systemUserService.findByUserId(userId);
        SystemDept dept = deptService.findById(user.getDeptId());
        model.addAttribute("dept", dept);
        model.addAttribute("user", user);
        return "user/info";
    }


    /* JSON API */

    @ApiOperation(value = "用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", defaultValue = "10", required = true)
    })
    @GetMapping("/list.json")
    @ResponseBody
    public Result<?> listForJson(int pageNum, int pageSize, @RequestParam Map params) {
        PageHelper.startPage(getRequest());
        System.out.println(params);
        List<SystemUser> users = systemUserService.list(params);
        PageInfo<SystemUser> pageInfo = new PageInfo<>(users);
        return ResultHelper.ok(pageInfo);
    }


    @ApiOperation(value = "添加用户")
    @PostMapping("/add.json")
    @ResponseBody
    public Result<?> addForJson(SystemUser user) {
        user = systemUserService.addUser(user);
        return ResultHelper.ok(user);
    }


    @ApiOperation(value = "删除用户")
    @ApiImplicitParam(name = "userIds", value = "用户ID", required = true)
    @DeleteMapping("/del")
    @ResponseBody
    public Result delete(String userIds) {
        long[] ids = StrUtil.splitToLong(userIds, ",");
        for (long id : ids) {
            systemUserService.deleteByUserId(id);
        }
        Result<Map<String, Object>> result = ResultHelper.ok();
        result.getData().put("userIds", ids);
        return result;
    }

    @ApiOperation(value = "更新用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "query")
    })
    @ApiParam(name = "userId", value = "用户ID", required = true)
    @PutMapping("/update")
    @ResponseBody
    public Result update(SystemUser user) {
        systemUserService.update(user);
        return ResultHelper.ok(user);
    }

    @ApiOperation(value = "更新用户状态")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true)
    )
    @PutMapping("/status")
    @ResponseBody
    public Result status(long userId) {
        SystemUser user = systemUserService.findByUserId(userId);
        user.setStatus(user.getStatus() == UserStatus.NORMAL.val ? UserStatus.LOCKED.val : UserStatus.NORMAL.val);
        systemUserService.update(user);
        Result<Map<String, Object>> result = ResultHelper.ok();
        result.getData().put("userId", userId);
        result.getData().put("status", user.getStatus());
        return result;
    }

    @ApiIgnore
    @GetMapping("/info.json")
    @ResponseBody
    public Result<SystemUser> info() {
        return ResultHelper.ok(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
    }

    @ApiIgnore
    @PutMapping("/password.json")
    @ResponseBody
    public Result password(long userId, String password) {
        SystemUser user = systemUserService.findByUserId(userId);
        user.setPassword(password);
        PasswordEncoder pe = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        user.setPassword(pe.encode(password));
        systemUserService.update(user);
        return ResultHelper.ok();
    }
}
